package com.iteaj.iot.client.codec;

import com.iteaj.iot.SocketMessage;
import com.iteaj.iot.client.ClientComponent;
import com.iteaj.iot.client.ClientConnectProperties;
import com.iteaj.iot.client.TcpSocketClient;
import com.iteaj.iot.codec.adapter.DelimiterBasedFrameMessageDecoderAdapter;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandler;

public class DelimiterBasedFrameClient extends TcpSocketClient {

    private int maxFrameLength;
    private boolean stripDelimiter;
    private boolean failFast;
    private ByteBuf[] delimiter;

    public DelimiterBasedFrameClient(ClientComponent clientComponent, ClientConnectProperties config
            , int maxFrameLength, boolean stripDelimiter, boolean failFast, ByteBuf... delimiter) {
        super(clientComponent, config);
        this.failFast = failFast;
        this.delimiter = delimiter;
        this.maxFrameLength = maxFrameLength;
        this.stripDelimiter = stripDelimiter;
    }

    @Override
    protected ChannelInboundHandler createProtocolDecoder() {
        return new DelimiterBasedFrameMessageDecoderAdapter(this.getMaxFrameLength()
                , this.isStripDelimiter(), this.isFailFast(), this.getDelimiter()) {

            @Override
            public Class<? extends SocketMessage> getMessageClass() {
                return DelimiterBasedFrameClient.this.getClientComponent().getMessageClass();
            }

            @Override
            public SocketMessage proxy(ChannelHandlerContext ctx, ByteBuf decode) throws Exception {
                return DelimiterBasedFrameClient.this.getClientComponent().proxy(ctx, decode);
            }

            @Override
            public SocketMessage doDecode(ChannelHandlerContext ctx, ByteBuf decode) {
                return DelimiterBasedFrameClient.this.getClientComponent().doDecode(ctx, decode);
            }

            @Override
            public SocketMessage createMessage(byte[] message) {
                return DelimiterBasedFrameClient.this.getClientComponent().createMessage(message);
            }
        };
    }

    public int getMaxFrameLength() {
        return maxFrameLength;
    }

    public boolean isStripDelimiter() {
        return stripDelimiter;
    }

    public boolean isFailFast() {
        return failFast;
    }

    public ByteBuf[] getDelimiter() {
        return delimiter;
    }
}
